import { HmacSHA1 } from 'crypto-js'

const getHashUrl = (axiosConfig, token) => {
  try {
    console.log(axiosConfig.url.indexOf ('getSoilInfo'));
    if (axiosConfig.url.indexOf ('getSoilInfo')!== -1)
      debugger
    let url = axiosConfig.url;
    const data = axiosConfig.data || {};
    const queryParams = {
      ...(getUrlQueryParamsToObj(url)|| {}),
      ...(axiosConfig.params || {})
    };
    const hasQueryParams = !!Object.keys(queryParams).length;
    const hasData = !!Object.keys(data).length
    let hash = ''
    let hashParams = ''

    /* if (!token)
      return url;
    if (!hasQueryParams && !hasData)
      return url; */


    if (hasQueryParams) {
      url = url.split('?')[0];
      Object.keys(queryParams).map(((k, i) => {
        let param = `${k}=${encodeURIComponent(queryParams[k])}`
        url += `${Number(i) ? '&' : '?'}${param}`
      }))
    }

    if (!hasQueryParams && axiosConfig.method === 'post') {
      /* const keys = Object.keys(data).filter(v => {
        return (typeof data[v] === 'string') || !isNaN(data[v])
      });
      if (!!keys.length) {
        const max = Math.min(5, keys.length)
        const indexList = getRandomList(max);
        let _keys = indexList.map(index => keys[index]);
        _keys.map((k, i) => {
          let param = `${k}=${data[k]}`
          url += `${Number(i) ? '&' : '?'}${param}`
        })
      } */
    }
    if (axiosConfig.method === 'get') {
      url += `${hasQueryParams ? '&' : '?'}r=${Math.random()}`;
      hashParams = url.replace ('dii/', '').replace ('cas-service/', '').replace ('device/', '').split('?')[0].replace (/^\//, '') + (token || '') + (url.split('?')[1] || '');
      hash = HmacSHA1(hashParams, '123@jinnong').toString();
    } else if (axiosConfig.method === 'post') {
      hashParams = url.replace ('dii/', '').replace ('cas-service/', '').replace ('device/', '').split('?')[0].replace (/^\//, '') + (token || '') + (hasData ? JSON.stringify(data) : (url.split('?')[1] || ''))
      hash = HmacSHA1(hashParams, '123@jinnong').toString();
    }
    /* console.log('=========');
    console.log('method=>>>', axiosConfig.method);
    console.log('url=>>>', url);
    console.log('hashParams=>>>', hashParams);
    console.log('hash=>>>', hash);
    console.log('========='); */
    hash = HmacSHA1(hashParams, '123@jinnong').toString();
    return url += `${(hasQueryParams ||  axiosConfig.method === 'get')? '&' : '?'}hash=${hash}`
  } catch (error) {
    console.error(error);
  }

}

const getUrlQueryParamsToObj = (url) => {
  if (!(url.split('?')[1])) {
    return {}
  }
  let str = JSON.stringify(
    url.split('?')[1]
      .split('&')
      .map(item => item.split('='))
  ).replace('[', '')
    .replace(/(.*)\]/, '$1')
    .replace(/\"\,\"/g, '":"')
    .replace(/\]\,\[/g, ',')
    .replace('[', '{')
    .replace(']', '}')
  return JSON.parse(str)
}

const getRandomList = (max) => {
  const arr = [];
  for (let i = 0; i < max; i++) {
    let random = getRadom(max);
    if (arr.find(num => num === random) !== undefined) {
      i--
    } else {
      arr.push(random)
    }
  }

  return arr;
}

const getRadom = (max) => {
  return Math.floor(Math.random() * max)
}

export { getHashUrl }; 